import { defineStore } from 'pinia';
import { getUser } from '@/api/user';
import { removeToken } from '@/utils/token';
import { reactive } from 'vue';

export const useTestStore = defineStore('user', () => {
  let state = reactive({
    userInfo: {},
    permissions: [],
  });
  const getters = {
    userId: () => state.userInfo?.id ?? '',
    name: () => state.userInfo?.name ?? '',
    avatar: () => state.userInfo?.avatar ?? '',
    role: () => state.userInfo?.role ?? [],
    getPermissions: () => state.userInfo?.role ?? [],
  };
  const actions = {
    async getUserInfo() {
      try {
        const res = await getUser();
        if (res?.code === 200) {
          const { id, name, avatar, role } = res.data;
          state.userInfo = { id, name, avatar, role };
          return Promise.resolve(res.data);
        } else {
          return Promise.reject(res.message);
        }
      } catch (error) {
        console.error(error);
        return Promise.reject(error.message);
      }
    },
    logout() {
      removeToken();
      state.userInfo = {};
    },
    setUserInfo(newUserInfo = {}) {
      state.userInfo = { ...state.userInfo, ...newUserInfo };
    },
  };
  return {
    state,
    getters,
    actions,
  };
});
